package com.atguigu.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.BaseDao.BaseDao;
import com.atguigu.BaseService.impl.BaseServiceImpl;
import com.atguigu.dao.AdminRoleDao;
import com.atguigu.dao.RoleDao;
import com.atguigu.entity.Admin;
import com.atguigu.entity.AdminRole;
import com.atguigu.entity.Role;
import com.atguigu.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl extends BaseServiceImpl<Role> implements RoleService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private AdminRoleDao adminRoleDao;

    @Override
    protected BaseDao<Role> getEntityDao() {
        return roleDao;
    }

    public List<Role> findAll() {

        return roleDao.findAll();
    }



    @Override
    public Map<String, Object> findRoleByAdminId(Long adminId) {

        //获取所有的角色
        List<Role> roleList = roleDao.findAll();
        // 获取拥有的用户id
        List<Long> roleIdList = adminRoleDao.findRoleByAdminId(adminId);
        //根据id分为已分配和未分配
        List<Role> noAssignRoleList = new ArrayList();
        List<Role> assignRoleList = new ArrayList();
        for (Role role : roleList) {
            if (roleIdList.contains(role.getId())){
                assignRoleList.add(role);
            }else {
                noAssignRoleList.add(role);

            }
        }
        //返回数据
        Map<String, Object> roleMap = new HashMap<>();
        roleMap.put("noAssignRoleList", noAssignRoleList);
        roleMap.put("assignRoleList", assignRoleList);
        return roleMap;
    }
    @Override
    public void saveUserRoleRealtionShip(Long adminId, Long[] roleIds) {
        adminRoleDao.deleteByAdminId(adminId);

        if (roleIds != null) {
            for (Long roleId : roleIds) {
                if (!StringUtils.isEmpty(roleId)) {
                    AdminRole adminRole = new AdminRole();
                    adminRole.setRoleId(roleId);
                    adminRole.setAdminId(adminId);
                    adminRoleDao.insert(adminRole);
                }
            }
        }
    }

}